package com.example.shiwu;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.os.StrictMode;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.chaquo.python.PyObject;
import com.chaquo.python.Python;
import com.chaquo.python.android.AndroidPlatform;
import com.example.shiwu.adapter.CheckAllAdapter;
import com.example.shiwu.db.dao.DeviceDao;
import com.example.shiwu.db.model.Arrange;
import com.example.shiwu.db.model.Device;
import com.example.shiwu.db.model.Items;
import com.example.shiwu.db.model.Sends;
import com.example.shiwu.db.vo.MyQueue;
import com.example.shiwu.manager.DatabaseHelper;
import com.example.shiwu.service.ArrangeService;
import com.example.shiwu.service.DeviceService;
import com.example.shiwu.service.ItemsService;
import com.example.shiwu.service.ReceiveService;
import com.example.shiwu.service.ReceiveVolEleService;
import com.example.shiwu.service.SendsService;
import com.example.shiwu.util.ArrayUtil;
import com.example.shiwu.util.ContextVariable;
import com.example.shiwu.util.DataParseUtil;
import com.example.shiwu.util.DateUtils;
import com.example.shiwu.util.ScreenUtil;
import com.example.shiwu.util.SocketQueueUtils;
import com.google.firebase.crashlytics.buildtools.reloc.com.google.common.base.Joiner;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import org.json.JSONException;

import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.util.IdUtil;

public class SendReceiveAddQueueActivity extends AppCompatActivity {
    private RefreshLayout mRefreshLayout;
    private ListView listView;
    private CheckBox checkBox;
    private CheckAllAdapter myAdapter;
    private DeviceService deviceService;
    private ItemsService itemsService;
    private ReceiveService receiveService;
    private Map<String, Object> showitem;
    private List<Map<String, Object>> listitem;
    private ArrayList<Device> deviceLisAll = new ArrayList<Device>();

    private int currentPage = 0;
    private int pageSize = 2;
    private int totalSize = 0;
    public ListView editSb;
    public TextView title_text, title_seting, send_sub_btn;
    public ImageView title_back;
    private boolean checkSta = false;
    private DatabaseHelper dbHelper;
    private DeviceDao deviceDao;
    private Context myContext;
    private TextView pop_close;
    private EditText send_voltage_val, send_repeat_val, send_duration_val,
            send_point_a_val, send_point_b_val, send_point_m_val, send_point_n_val, clear_all_mux_box_connect_val;
    private Spinner send_frequency_val;
    private PopupWindow mPopWindow;
    private SendsService sendsService;
    private ArrangeService arrangeService;
//    private TextView pop_close;

    private final String TAG = "SendReceiveActivity";
    private static final String IP_ADDRESS = "ip_address";
    private static final String CLIENT_PORT = "client_port";
    private static final String CLIENT_MESSAGETXT = "client_msgtxt";


    private HandlerThread mHandlerThread;
    //子线程中的Handler实例。
    private Handler mSubThreadHandler;

    private final int STATE_DISCONNECTED = 1;
    private final int STATE_CONNECTING = 2;
    private final int STATE_CONNECTED = 3;
    private SharedPreferences mSharedPreferences;
    private SharedPreferences.Editor editor;
    private int mSocketConnectState = STATE_DISCONNECTED;

    private static final int MSG_TIME_SEND = 1;
    private static final int MSG_SOCKET_CONNECT = 2;
    private static final int MSG_SOCKET_DISCONNECT = 3;
    private static final int MSG_SOCKET_CONNECTFAIL = 4;
    private static final int MSG_RECEIVE_DATA = 5;
    private static final int MSG_SEND_DATA = 6;
    private static final int MSG_SEND_DATA_BYTE = 7;
    private static final int MSG_RECEIVE_TU_DATA = 8;
    private static final int MSG_RECEIVE_TU_NEW_DATA = 9;
    private static final int MSG_RECEIVE_POP_DATA = 10;

    private static final int MSG_SEND_DATA_BYTE_RECEIVE = 1;//硬件成功返回信息
    private TextView receive_voltage;
    private Python py;
    private PyObject pyobj, pyobj1, pyplot, pyobj2, pyobj3, pyobjfft;
    private byte[] bytesData;
    private byte[] data, data2, data3;
    private Boolean startGater = false;

    private Integer rx_voltage_data_len = 0;
    private String simpleUUID = "";
    private String sf = "";

    private Integer rec_count_s = 0;
    private Integer packet_indx = 0;
    private int packet_indx1 = 0;
    private Integer old_packet_lens = 0;
    private Integer packet_lens = 0;//总包数 1536倒计数到0 packet_lens=0, bak_packet_lens=512, rec_count=512 self.send("kConfirm",rec_count)
    //private Integer bak_packet_lens = 0; //1536倒计数 bak_packet_lens=512, rec_count=512 self.send("kConfirm",rec_count)
    private int packet_lens_old = 0;
    private int receive_count = 0;//用与截取0，success;10,1,10;的标识
    public int length_byte = 0;//合并Byte
    //private String no_id_str = "";//不包含数据头 10.1024,12
    public byte[] all_byte;
    public byte[] all_byte_de_weight; //去/,后的byte[]
    public String receiveDataAll = "";
    public ArrayList<byte[]> all_byte_lis;
    public int count_byte = 0;
    public int byte_len = 0;
    private String cmd_index_len = "";//消息的id 10
    private boolean next_sta = false;
    private boolean back_over = false; //biaoshi
    private boolean byte_sta = false;//组装数据用，完全组装后 true
    private View contentView;
    private String tx_voltage = "";//发送电压
    private String tx_current = "";//发射电流
    private String rx_voltage = "";//接受电压
    private ImageView mChart1;
    private TextView send_voltage_pop_val, send_repeat_pop_val, send_freq_pop_val, receive_duration_pop_val;
    private String strData;//接收总数据数据，拼接完整数据后再解析
    private StringBuffer stringBufferData;//接收总数据数据，拼接完整数据后再解析

    private Boolean bl = false;

    private Boolean bool = false;
    private String[] freqData;
    private int header_cou = 0;
    private int loding_count = 0;
    private String sta = "";
    private int success_count = 0;
    private int receive_packet_indx_count = 0;
    //private Boolean bool1 = true;
    private int abmn_indx = 0;
    private byte[] buffer_new = new byte[1];
    private boolean read_byte_sta = false;
    private MyQueue queue;
    private int msg_sueecss_count = 0;
    public Boolean receive_one_field_sta = true;
    Boolean returnSta = true;

    //private int indx=0;
    private String tx_voltage_data = "";
    private String tx_current_data = "";
    private String rx_voltage_data = "";
    private String vol_ele_noindx = "";
    private String vol_ele = ContextVariable.vol_ele;
    private Boolean receive_sta = false;//采集一次后true 过滤vol_ele的title
    private int inclickGatherCount;//点击采集按钮次数
    private ReceiveVolEleService receiveVolEleService;
    private SocketQueueUtils SocketQueueUtils;
    private String dtype, shape, abmn;
    private int dtypelen, dtypelen0;
    private String[] clearStrLisAll;
    public MyThread myThread;
    public Boolean recv_float_bool = false;
    private String rx_voltage_data_all = "";

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_TIME_SEND:
                    break;

                case MSG_RECEIVE_DATA:
                    break;
                case MSG_RECEIVE_TU_DATA://采集数据展示图形

                    //生成的是不带-的字符串，类似于：b17f24ff026d40949c85a24f4f375d42
                    //String simpleUUID = IdUtil.simpleUUID();
                    String obj1 = (String) msg.obj;
                    byte[] ios = obj1.getBytes();
                    String pyBytes = DataParseUtil.jb2pb(ios);
                    byte[] data1 = pyobjfft.callAttr("draw_fft_square_wave", obj1, sf, rx_voltage_data_len).toJava(byte[].class);
                    mChart1.setImageBitmap(BitmapFactory.decodeByteArray(data1, 0, data1.length));
//                    new Thread(new Runnable() {
//                        @Override
//                        public void run() {
//                            String[] vel = vol_ele.split(";");
//                            FileDownUtil.saveFile(myContext, vel, simpleUUID);
//                            queue = new MyQueue();
//                            List<ReceiveVolEle> lis = new ArrayList<ReceiveVolEle>();
//                            ReceiveVolEle rve = null;
//                            MyQueue queue1 = new MyQueue();
//                            int ii = 0;
//                            if (!receive_sta) {
//                                ii = 1;
//                            }
//                            for (int i = ii; i < vel.length; i++) {
//                                String vel_new = vel[i];
//                                if (!vel_new.equals("")) {
//                                    String[] vel_new_lis = vel_new.split(",");
//                                    rve = new ReceiveVolEle();
//                                    for (int j = 0; j < vel_new_lis.length; j++) {
//                                        switch (j) {
//                                            case 1:
//                                                rve.setIndx(Integer.parseInt(vel_new_lis[j]));
//                                                rve.setCreateTime(DateUtils.parseDate());
//                                                rve.setGropId(simpleUUID);
//                                                Items items = findSelectItem();
//                                                rve.setItemId(items.getId());
//                                                break;
//                                            case 7:
//                                                rve.setTxv(vel_new_lis[j]);
//                                                break;
//                                            case 8:
//                                                rve.setTxc(vel_new_lis[j]);
//                                                break;
//
//                                            case 9:
//                                                rve.setRxv(vel_new_lis[j]);
//                                                break;
//                                        }
//
//                                    }
//                                    lis.add(rve);
//                                    queue1.enQueue(rve);
//                                    ReceiveVolEle rveDo = (ReceiveVolEle) queue1.deQueue();
//                                    //queue.clear();
//                                    if (rve != null && rve.getIndx() != null) {
//                                        receiveVolEleService.save(rve);
//                                    }
//                                    receive_sta = true;
//                                    System.out.println("socketUtil_statu =============================" + SocketQueueUtils.socket.isConnected());
//                                }
//
//                            }
//                        }
//                    }).start();


                    break;
                case MSG_RECEIVE_TU_NEW_DATA:
                    //byte[] data4 = pyobj1.callAttr("onKConfirmToMcu", rec_count_s).toJava(byte[].class);
                    //sendByte(data4);
                    break;
                case MSG_RECEIVE_POP_DATA:
                    Boolean bool = showPopupWindow();
//                    byte[] data6 = pyobj1.callAttr("onKConfirmToMcu",rec_count).toJava(byte[].class);
//                    sendByte(data6);
                    break;
                default:
                    break;
            }
        }

        ;
    };


    /**
     * 定义文件保存的方法，写入到文件中，所以是输出流
     */
    public void saveFile(String[] vel, String simpleUUID) {

        String content = "";
        FileOutputStream fos = null;
        try {
            // Context.MODE_PRIVATE私有权限，Context.MODE_APPEND追加写入到已有内容的后面
            fos = myContext.openFileOutput(getFileName(simpleUUID), Context.MODE_APPEND);
            String content1 = vel[0];
            if (!content1.equals("") && content1.length() > 0) {//cvs头
                fos.write(content1.getBytes());
            }

            for (int i = vel.length - 1; i >= 0; i--) {//cvs数据
                if (i > 0) {
                    if (!vel[i].contains("\n")) {
                        content = vel[i];
                    } else {
                        content = vel[i].substring(1);
                    }
                    fos.write(content.getBytes());
                    fos.write("\r\n".getBytes());//写入换行
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * get file name such as 20171031.txt
     *
     * @return
     */
    private String getFileName(String simpleUUID) {
        Items items = findSelectItem();
        return items.getId() + "-" + simpleUUID + ".cvs";
    }

//    private void savebitmap(Bitmap bitmap) {
//
//        //创建文件，因为不存在2级目录，所以不用判断exist，要保存png，这里后缀就是png，要保存jpg，后缀就用jpg
//        File file = new File(Environment.getExternalStorageDirectory() + "/mfw.png");
//        try {
//            //文件输出流
//            FileOutputStream fileOutputStream = new FileOutputStream(file);
//            //压缩图片，如果要保存png，就用Bitmap.CompressFormat.PNG，要保存jpg就用Bitmap.CompressFormat.JPEG,质量是100%，表示不压缩
//            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
//            //写入，这里会卡顿，因为图片较大
//            fileOutputStream.flush();
//            //记得要关闭写入流
//            fileOutputStream.close();
//            //成功的提示，写入成功后，请在对应目录中找保存的图片
//            System.out.println("写入成功！目录" + Environment.getExternalStorageDirectory() + "/mfw.png");
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//            //失败的提示
//            System.out.println("写入失败！目录" + Environment.getExternalStorageDirectory() + "/mfw.png");
//        } catch (IOException e) {
//            e.printStackTrace();
//            //失败的提示
//            System.out.println("写入失败！目录" + Environment.getExternalStorageDirectory() + "/mfw.png");
//        }
//
//    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //退出HandlerThread的Looper循环。
        System.out.println("---------------------- onDestroy --------------------");
        SocketQueueUtils.success_count = 0;
        //SocketQueueUtils.buffer = null;
        SocketQueueUtils.releaseSocket();
        msg_sueecss_count = 0;
        startGater = false;

    }


    private Boolean recv_float_array_with_indx() throws InterruptedException, IOException {
//        Timer timer = new Timer();
//        TimerTask task = new TimerTask() {
//            @Override
//            public void run() {
//                SocketQueueUtils.success_count = 6;
//                byte[] data4 = pyobj1.callAttr("onKConfirmToMcu", SocketQueueUtils.packet_indx).toJava(byte[].class);
//                SocketQueueUtils.writeMsgByte(data4);
//                System.out.println(" 超时重复开始= " + DateUtils.parseYmdHmsDate());
//            }
//        };
        int status = 0;
        int error = 0;
        int rec_count = 0;
        int bak_packet_lens = 0;
        int bak_indx = 0;
//        int A = 1;
//        int B = 2;
//        int M = 4;
//        int N = 5;
        returnSta = false;
        recv_float_bool = true;
//        ArrayList<Float> tx_current = new ArrayList<Float>();
//        ArrayList<Float> rx_voltage = new ArrayList<Float>();
//        ArrayList<Float> tx_voltage = new ArrayList<Float>();
        //Thread.sleep(1450);
        //mReceiveThread.pauseThread();
        while (recv_float_bool) {
            //if (queue != null) {
            //Log.i("buffer","-------------success_count = "+SocketQueueUtils.success_count );
            if (SocketQueueUtils.success_count > 7) {
                bak_packet_lens = SocketQueueUtils.packet_lens_old / 3;
                error = 0;
                //接收包头AA55
                receive_one_field_sta = true;
                Map<String, Object> map = receive_one_field1("AA55");
                receive_one_field_sta = false;
                List<Byte> ab1 = DataParseUtil.objToByList(map.get("one_field"));

                byte[] str_one_field = DataParseUtil.listTobyte(ab1);
                //System.out.println("--------------------str_one_field1--------------------" + ab1.toString());
                Boolean timeout = (Boolean) map.get("timeout");
//                if(receive_packet_indx_count == 1){
//                    System.out.println("--------------------head-str_one_field--------------------" + map.get("one_field").toString());
//                }

                if (timeout) {
                    error = error + 1;
                    break;
                }

                if (str_one_field.length > 0) {
                    //System.out.println("--------------------str_one_field000--------------------");

                    // System.out.println("--------------------str_one_field111--------------------");
                    int str_lens = DataParseUtil.entiretyDecodeStructByteBack(str_one_field);
                    if (str_one_field[0] == 0) {
                        continue;
                    } else if (str_lens < 2) {
                        //System.out.println("header len error " + str_one_field);
                        //System.out.println("last indx= " + bak_indx);
                        continue;
                    } else if (str_lens > 2) {
                        error = error + 1;
                        //System.out.println("header len >4, break: " + str_one_field);
                        break;
                    } else {
                        int header = recv_unsigned_int(str_one_field);
                        // vol_ele += ContextVariable.freq + ",";
                        //vol_ele += packet_indx + ",";
                        //System.out.println("00000000000000000000 header= " + header);
                        if (header != 0xAA55) {
                            System.out.println("header error " + new String(str_one_field));
                            continue;
                        }
                    }
                }

                //接收包的indx
                //需要对接收到的_receive_one_field的长度做判断，如果长度不够，就认为接收出错
                receive_one_field_sta = true;
                Map<String, Object> map2 = receive_one_field1("indx");
                receive_one_field_sta = false;
                List<Byte> ab2 = DataParseUtil.objToByList(map2.get("one_field"));
                byte[] str_one_field2 = DataParseUtil.listTobyte(ab2);
                Boolean timeout2 = (Boolean) map2.get("timeout");
                //System.out.println("--------------------str_one_field2--------------------" + ab2.toString());
                if (timeout2) {
                    error = error + 1;
                    break;
                }
                int indx = 0;
                if (str_one_field2.length > 0) {
                    int str_lens = DataParseUtil.entiretyDecodeStructByteBack(str_one_field2);
                    if (str_lens != 2) {
                        error = error + 1;
                    } else {
                        indx = recv_unsigned_int(str_one_field2);
                        //vol_ele += indx + ",";
                        //vol_ele += A + ",";
                        //vol_ele += B + ",";
                        // vol_ele += M + ",";
                        //vol_ele += N + ",";
                        //System.out.println("-------str_one_field2--indx--- " + indx);

                        if (indx > bak_packet_lens) {
                            error = error + 1;
                            break;
                        }

                    }
                }

                //tx_voltage_data

                receive_one_field_sta = true;
                Map<String, Object> map3 = receive_one_field1("tx_voltage_data");
                receive_one_field_sta = false;
                List<Byte> ab3 = DataParseUtil.objToByList(map3.get("one_field"));
                byte[] str_one_field3 = DataParseUtil.listTobyte(ab3);
                Boolean timeout3 = (Boolean) map3.get("timeout");
                //System.out.println("--------------------str_one_field3--------------------" + ab3.toString());
                if (timeout3) {
                    error = error + 1;
                    break;
                }
                String tx_voltage1 = null;
                if (str_one_field3.length > 0) {
                    int str_lens = DataParseUtil.entiretyDecodeStructByteBack(str_one_field3);
                    if (str_lens != 4) {
                        error = error + 1;
                        break;
                    } else {
                        tx_voltage1 = recv_float(str_one_field3);
                        //System.out.println("--------------------tx_voltage1--------------------" + tx_voltage1);
                        //vol_ele += tx_voltage1 + ",";
                    }
                }

                //tx_current_data

                receive_one_field_sta = true;
                Map<String, Object> map4 = receive_one_field1("tx_current_data");
                receive_one_field_sta = false;
                List<Byte> ab4 = DataParseUtil.objToByList(map4.get("one_field"));
                byte[] str_one_field4 = DataParseUtil.listTobyte(ab4);
                Boolean timeout4 = (Boolean) map4.get("timeout");
                //System.out.println("--------------------str_one_field4--------------------" + ab4.toString());
                if (timeout4) {
                    error = error + 1;
                    break;
                }
                String tx_current1 = null;
                if (str_one_field4.length > 0) {
                    int str_lens = DataParseUtil.entiretyDecodeStructByteBack(str_one_field4);
                    if (str_lens != 4) {
                        error = error + 1;
                        break;
                    } else {
                        tx_current1 = recv_float(str_one_field4);
                        //System.out.println("--------------------tx_current1--------------------" + tx_current1);
                        //vol_ele += tx_current1 + ",";
                        //vol_ele_noindx += tx_current1 + ",";
                    }
                }

                //rx_voltage_data

                int indx_end = 0;
                receive_one_field_sta = true;

                Map<String, Object> map5 = receive_one_field1("rx_voltage_data");
                //System.out.println(indx);
                receive_one_field_sta = false;
                List<Byte> ab5 = DataParseUtil.objToByList(map5.get("one_field"));
                byte[] str_one_field5 = DataParseUtil.listTobyte(ab5);
                Boolean timeout5 = (Boolean) map5.get("timeout");
                //System.out.println("--------------------str_one_field5--------------------" + ab5.toString());

                if (timeout5) {
                    error = error + 1;
                    break;
                }
                String rx_voltage1 = null;

                if (str_one_field5.length > 0) {
                    int str_lens = DataParseUtil.entiretyDecodeStructByteBack(str_one_field5);
                    if (str_lens != 4) {
                        error = error + 1;
                        break;
                    } else {
                        rx_voltage1 = recv_float(str_one_field5);
                        //System.out.println("--------------------rx_voltage1--------------------" + rx_voltage1);
                        //vol_ele += rx_voltage1 + ";\n";
                        //vol_ele_noindx += rx_voltage1 + ",";
                    }
                }

                rec_count = rec_count + 1;

                //tx_voltage_data += tx_voltage1 + ",";
                //tx_current_data += tx_current1 + ",";
                rx_voltage_data += rx_voltage1 + ",";
                SocketQueueUtils.packet_lens -= 3;
                // String str = vol_ele_noindx.substring(0, vol_ele_noindx.length() - 1);
                //rx_voltage_data_len = rx_voltage_data.substring(0, rx_voltage_data.length() - 1).split(",").length;
                //System.out.println("index ====== " + indx + " ======SocketQueueUtils.packet_lens== " + SocketQueueUtils.packet_lens + " == " + queue.QueueLength() + " = " + bool);
                if(indx <= 10){
                    System.out.println("index ====== " + indx + " ======SocketQueueUtils.packet_lens== " + SocketQueueUtils.packet_lens + " == " + queue.QueueLength() + " = " + bool);

                }

                if (SocketQueueUtils.packet_lens <= 0) {
//                    System.out.println("------------------------bak_packet_lens-------------------  "+bak_packet_lens);
//                    System.out.println("------------------------rec_count-------------------  "+rec_count);
                    if (bak_packet_lens == rec_count) {
                        System.out.println(" =============== 4,start; 结束= " + DateUtils.parseYmdHmsDate());
                        //System.out.println(rx_voltage_data);
                        recv_float_bool = false;
                        receive_one_field_sta = false;

                        SocketQueueUtils.resumeThread();
                        SocketQueueUtils.success_count = 6;


                        byte[] data4 = pyobj1.callAttr("onKConfirmToMcu", rec_count).toJava(byte[].class);
                        SocketQueueUtils.writeMsgByte(data4);
                        System.out.println(" 重复开始= " + DateUtils.parseYmdHmsDate());
                        //timer.schedule(task,0,3000);
//                        try {
//                            Thread.sleep(10);
//                        } catch (InterruptedException e) {
//                            throw new RuntimeException(e);
//                        }
                        recv_float_bool = true;
                        receive_one_field_sta = true;

                        //System.out.println(" 点击结束= " + DateUtils.parseYmdHmsDate());
                        SocketQueueUtils.packet_indx -= 1;
                        rec_count_s = rec_count;
                        rec_count = 0;
                        back_over = true;
                        receive_packet_indx_count += 1;
                        rx_voltage_data_all += rx_voltage_data + ";";
                        //sendTxt("22,S;");
                        //System.out.println("rx_voltage_data+++++ "+rx_voltage_data);
                        if (SocketQueueUtils.packet_indx == 0) {
                            String[] rxStrList = rx_voltage_data_all.split(";");
                            String rx_voltage_data_add = ArrayUtil.strToStrArrrayAdd(rxStrList);
                            rx_voltage_data_len = rx_voltage_data_add.substring(0, rx_voltage_data_add.length() - 1).split(",").length;
                            if (!rx_voltage_data_add.equals("")) {
                                Message msg = new Message();
                                msg.what = MSG_RECEIVE_TU_DATA;
                                msg.obj = rx_voltage_data_add;
                                mHandler.sendMessage(msg);
                            }

                            rx_voltage_data_all = "";
                            rx_voltage_data = "";
                            returnSta = true;
                            break;
                        }
                        //返回正确确认包，
                        status = 0;

                    } else {
//                        byte[] data4 = pyobj1.callAttr("onKConfirmToMcu", 0).toJava(byte[].class);
//                        SocketQueueUtils.writeMsgByte(data4);
                        status = 1;
                    }
                }

            }
            //}
        }
        if (error > 0) {
            System.out.println("=================error > 0================");
            bool = false;
            //Thread.sleep(1500);
            status = 1;
            byte[] data4 = pyobj1.callAttr("onKConfirmToMcu", SocketQueueUtils.packet_indx).toJava(byte[].class);
            SocketQueueUtils.writeMsgByte(data4);
            System.out.println("=================error > 11111111111111111================");
        }
        return returnSta;
    }

    private Map<String, Object> receive_one_field1(String name) throws InterruptedException {
        Map<String, Object> map = new HashMap<>();
        Boolean escaped = false;
        Boolean command_sep_found = false;
        ArrayList<Byte> one_field = new ArrayList<Byte>();
        Boolean timeout = false;

        while (receive_one_field_sta) {
//            Thread.sleep(0);
            if (queue.QueueEmpty()) {
                //System.out.println("queue 是空队列 = " + queue.QueueEmpty()+" ----  mTheead ="+mReceiveThread.getState());
            } else {
                //Log.i("队列", "9999999999999999999999------- queue=" + queue.QueueEmpty());
                if (queue.QueueLength() > 0) {
                    if (queue.QueueLength() == 0) {
                        break;
                    }

                    byte tmp = (byte) queue.deQueue();

                   // System.out.println("9999999999999999999999------- tmp=" + tmp);
                    // System.out.println("9999999999999999999999------- name=" + name);
                    //System.out.println("queue 不是空 = " + queue.QueueEmpty()+" ----  mTheead ="+mReceiveThread.getState());


                    if (escaped) {
                        if (tmp == 44 || tmp == 59 || tmp == 47) {
                            one_field.add(tmp);
                            escaped = false;
                        } else {
                            one_field.add(tmp);
                            escaped = false;
                        }
                    } else {
                        if (tmp == 47) {
                            //遇到 / 就escaped = True 继续循环
                            escaped = true;
                        } else if (tmp == 44) {
                            break;
                        } else if (tmp == 59) {
                            command_sep_found = true;
                            break;
                        } else {
                            one_field.add(tmp);
                        }
                    }
                }
            }
        }
        map.put("one_field", one_field);
        map.put("timeout", timeout);
        return map;
    }

    private synchronized Map<String, Object> receive_one_field(String name) throws InterruptedException {
        Map<String, Object> map = new HashMap<>();
        Boolean escaped = false;
        Boolean command_sep_found = false;
        ArrayList<Byte> one_field = new ArrayList<Byte>();
        Boolean timeout = false;

        while (receive_one_field_sta) {
            byte tmp = SocketQueueUtils.read();
            //System.out.println("9999999999999999999999------- tmp=" + tmp);
//            if(tmp == 0){
//                continue;
//            }
            //System.out.println("9999999999999999999999------- tmp=" + tmp);
            // System.out.println("9999999999999999999999------- name=" + name);
            //System.out.println("queue 不是空 = " + queue.QueueEmpty()+" ----  mTheead ="+mReceiveThread.getState());

            if (escaped) {
                if (tmp == 44 || tmp == 59 || tmp == 47) {
                    one_field.add(tmp);
                    escaped = false;
                } else {
                    one_field.add(tmp);
                    escaped = false;
                }
            } else {
                if (tmp == 47) {
                    //遇到 / 就escaped = True 继续循环
                    escaped = true;
                } else if (tmp == 44) {
                    break;
                } else if (tmp == 59) {
                    command_sep_found = true;
                    break;
                } else {
                    one_field.add(tmp);
                }
            }
            //tmp = Byte.parseByte(null);
        }
        map.put("one_field", one_field);
        map.put("timeout", timeout);

        return map;
    }

    private Integer recv_unsigned_int(byte[] val) {

        return DataParseUtil.recv_unsigned_int(val);
    }

    private String recv_float(byte[] val) {
        return DataParseUtil.recv_float(val);
    }


    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                SocketQueueUtils = new SocketQueueUtils();
                SocketQueueUtils.success_count = 0;
                SocketQueueUtils.receiveDataAll = "";
                socketListener();

            }
        }).start();


        //SocketQueueUtils = SocketQueueUtils.getInstance();
        //SocketQueueUtils.releaseSocket();


        setContentView(R.layout.send_receive_add);
        arrangeService = new ArrangeService();
        myContext = this;
        deviceDao = new DeviceDao();
        all_byte_lis = new ArrayList<byte[]>();
        stringBufferData = new StringBuffer();
        title_back = findViewById(R.id.title_back);
        title_text = findViewById(R.id.title_text);
        title_seting = findViewById(R.id.title_setting);
        title_text.setText("发射接收信息");
        title_seting.setVisibility(View.INVISIBLE);
        receive_voltage = findViewById(R.id.receive_voltage_val);

        send_sub_btn = findViewById(R.id.send_sub_btn);
        receiveService = new ReceiveService();
        deviceService = new DeviceService();
        itemsService = new ItemsService();
        listitem = new ArrayList<Map<String, Object>>();
        SharedPreferences sp = this.getSharedPreferences(this.getPackageName(), Activity.MODE_PRIVATE);
        String ips = sp.getString("ip", "");
        initTextView();
        initData();
        //HexBinary();
        Resources res = getResources();
        freqData = res.getStringArray(R.array.freqData);
        queue = new MyQueue();
        mSharedPreferences = getSharedPreferences("setting", Context.MODE_PRIVATE);


        //获取保存的ip地址、客户端端口号
        //mIpAddress = mSharedPreferences.getString(IP_ADDRESS, null);
        //mClientPort = mSharedPreferences.getInt(CLIENT_PORT, DEFAULT_PORT);
        title_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SendReceiveAddQueueActivity.this.finish();
            }
        });

        send_sub_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (send_voltage_val.length() > 0) {
//                    if (send_voltage_val.length() > 0 &&
//                            send_duration_val.length() > 0) {
                    //System.out.println(" 点击开始= " + DateUtils.parseYmdHmsDate());
                    try {
                        getTexts();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    //ProgressDialogUtils.showProgressDialog(myContext,"采集中...");
                } else {
                    Toast.makeText(myContext, "发射信息不能为空！", Toast.LENGTH_SHORT).show();
                }
            }
        });

        try {
            initPython(this);
            //NetWorkUtil.getApIpAddress2();
            //pyMain();
        } catch (JSONException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    private void initTextView() {
        send_voltage_val = findViewById(R.id.send_voltage_val);
        send_repeat_val = findViewById(R.id.send_repeat_val);
        send_frequency_val = findViewById(R.id.send_frequency_val);
        //send_duration_val = findViewById(R.id.send_duration_val);
        //clear_all_mux_box_connect_val = findViewById(R.id.clear_all_mux_box_connect_val);
    }

    private void socketListener() {

        if (SocketQueueUtils != null) {
            // 启动监听
            SocketQueueUtils.startListening();
            // 设置消息监听器
            SocketQueueUtils.setOnMessageReceivedListener(new SocketQueueUtils.OnMessageReceivedListener() {
                @Override
                public void onMessageReceived(byte[] message) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //System.out.println("======================== SocketQueueUtils ================" + SocketQueueUtils == null);
                            System.out.println("======================== onMessageReceived ================" + message.length);
                            for (int i = 0; i < message.length; i++) {
                                // 在UI线程更新消息
                                queue.enQueue(message[i]);
                                //System.out.println("======================== onMessageReceived queue ================" + queue.QueueLength());
                            }

                        }
                    });
                }

                @Override
                public void onMessageReceivedString(String message) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // System.out.println("======================== success or bad_param ================" + message);
                            if (message.equals("None")) {
                                System.out.println(" usb/wifi connect error ");
                                return;
                            }
                            if (message.contains("0,Success;") && !message.equals("")) {
                                msg_sueecss_count += 1;
                                switch (msg_sueecss_count) {
                                    case 2: //kSetTxWaveWithParam 3
                                        if (data != null) {
                                            SocketQueueUtils.writeMsgByte(data);
                                        }
                                        break;
                                    case 3://kClearAllMuxBoxConnect 15
                                        if (data != null) {
                                            SocketQueueUtils.writeMsgByte(data2);
                                        }
                                        break;
                                    case 4://kSetMuxBoxConnect 2
                                        if (data != null) {
                                            SocketQueueUtils.writeMsgByte(data3);
                                        }
                                        break;
                                    case 5:
                                        if (data != null) {
                                            SocketQueueUtils.writeMsg("23,r;");
                                        }
                                        break;
                                    case 6:
                                        if (data != null) {
                                            SocketQueueUtils.writeMsg("4,start;");

                                            //timer.schedule(task,0,4000);
                                            //timer.cancel();
                                            System.out.println(" =============== 4,start; 开始= " + DateUtils.parseYmdHmsDate());
                                            startGater = true;
                                            myThread.resumeThread();
                                        }
                                        break;
                                }
                            } else if (message.contains("Timeout")) {
                                System.out.println(" kSetMuxBoxConnect switch box connect error ");
                            } else if (message.equals("0,Bad_Param;")) {
                                System.out.println("======================== bad_param ================" + message);
                            }
                        }
                    });
                }

                @Override
                public void onConnectionLost() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // 处理连接中断的情况，例如显示提示或重新连接
                            //handleConnectionLost();
                            System.out.println(" socket 断开==================================");
                        }
                    });
                }
            });


        }
    }

    private void getTexts() throws InterruptedException {
        if (SocketQueueUtils == null) {
            SocketQueueUtils = SocketQueueUtils.getInstance();
            socketListener();
        }
        if (queue == null) {
            queue = new MyQueue();
        }
        if (inclickGatherCount > 0) {
            Thread.sleep(1000);
        }
        SocketQueueUtils.success_count = 1;
        myThread = new MyThread();

        packet_indx1 = Integer.parseInt(String.valueOf(send_repeat_val.getText()));
        packet_indx = packet_indx1;
        Sends sends = new Sends();
        sends.setVoltage(String.valueOf(send_voltage_val.getText()));
        sends.setType(0);
        sends.setStatus(0);
        sends.setRepeatNum(String.valueOf(send_repeat_val.getText()));
        sends.setSendFrequency(String.valueOf(send_frequency_val.getSelectedItemPosition()));
        sf = String.valueOf(send_frequency_val.getSelectedItemPosition() + 1);
        //sends.setSendDuration(String.valueOf(send_duration_val.getText()));

        Items items = findSelectItem();
        sends.setItemId(items.getId());
        SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date = new Date(System.currentTimeMillis());
        sends.setCreateTime(sim.format(date));
        sends.setUpdateTime(sim.format(date));
        simpleUUID = IdUtil.simpleUUID();
        sends.setUid(simpleUUID);
        sendsService = new SendsService();
        receiveVolEleService = new ReceiveVolEleService();
        String clearStr = clear_all_mux_box_connect_val.getText().toString();
        String[] clearStrLis = clearStr.split(",");
        int cslen = clearStrLis.length;
        int csnewlen = 10 - clearStrLis.length;
        String[] clearStrLisNew = new String[csnewlen];
        List<String> list = null;
        if (clearStrLis.length > 0 && clearStrLis.length < 10) {

            for (int i = 0; i < csnewlen; i++) {
                clearStrLisNew[i] = String.valueOf(0);
            }
            list = new ArrayList(Arrays.asList(clearStrLis));
            list.addAll(Arrays.asList(clearStrLisNew));
        } else {
            list = new ArrayList(Arrays.asList(clearStrLis));
        }
        String join2 = Joiner.on(",").join(list);
       // sends.setBoxaddr(join2);
        Object[] c = list.toArray();
        clearStrLisAll = Arrays.toString(c).replace("[", "").replace("]", "").split(",");
        Arrange arrange1 = new Arrange();
        arrange1.setItemId(items.getId());
        List<Arrange> arrangeLis = arrangeService.getArrange(arrange1);
        Integer ns = 0;

        if (arrangeLis.size() == 0) {
            Toast.makeText(myContext, "请先添加排列设计！", Toast.LENGTH_SHORT).show();
            return;
        } else {
            ns = arrangeLis.get(0).getDeviceTypeLen();
            dtype = arrangeLis.get(0).getDtype();
            dtypelen = arrangeLis.get(0).getDeviceTypeLen();
            shape = arrangeLis.get(0).getShape();
            abmn = arrangeLis.get(0).getDeviceTypeVal();
            dtypelen0 = dtypelen;
        }


        int countItem = findItemCount();

        if (countItem > 0) {
            boolean bl = sendsService.save(sends);
            if (bl) {
                Toast.makeText(myContext, "保存成功！", Toast.LENGTH_SHORT).show();
                SharedPreferences.Editor editor = mSharedPreferences.edit();
                editor.putInt("header_count", 0);
                editor.remove("header");// 初始化清空header
                showPopupWindow();//pop弹框
                myThread.start();
            }

        } else {
            Toast.makeText(myContext, "请先创建项目！", Toast.LENGTH_SHORT).show();

        }

    }

    class MyThread extends Thread {
        public final Object lock = new Object();
        public boolean threadExit;


        public MyThread() {
            threadExit = false;
        }

        /**
         * 调用这个方法实现暂停线程
         */
        public void pauseThread() {
            threadExit = true;
        }

        /**
         * 调用这个方法实现恢复线程的运行
         */
        public void resumeThread() {
            threadExit = false;
            synchronized (lock) {
                lock.notifyAll();
            }
        }

        public void threadExit() {
            threadExit = true;
        }

        /**
         * 注意：这个方法只能在run方法里调用，不然会阻塞主线程，导致页面无响应
         */
        public void onPause() {
            synchronized (lock) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void run() {
            System.out.println("---------------dtypelen---" + dtypelen);
            while (returnSta) {
                msg_sueecss_count = 2;
                //returnSta = false;
                String abmnStr = "";
                if (inclickGatherCount == 0) {
                    System.out.println("---------------dtypelen2---" + 0);
                    abmnStr = pyobj1.callAttr("subABMN", abmn, dtype, shape, 0).toJava(String.class);
                } else {
                    int dtypelen1 = dtypelen0 - 1;
                    //System.out.println("---------------dtypelen1---"+dtypelen1);
                    int dtypelen2 = dtypelen - dtypelen1;
                    System.out.println("---------------dtypelen2---" + dtypelen2);
                    if (dtypelen2 == dtypelen) {
                        returnSta = false;
                        return;
                    }
                    dtypelen0 = dtypelen1;
                    //System.out.println("---------------dtypelen0---"+dtypelen0);
                    abmnStr = pyobj1.callAttr("subABMN", abmn, dtype, shape, dtypelen2).toJava(String.class);
                }

                String[] abmnlis = null;
                if (abmnStr.length() > 0) {
                    abmnlis = abmnStr.split(",");
                }

                //kSetTxWaveWithParam 3
                if (inclickGatherCount == 0) {
                    data = pyobj1.callAttr("onSendParamToMcu", "1", send_frequency_val.getSelectedItemPosition() + 1, packet_indx1, send_voltage_val.getText().toString()).toJava(byte[].class);

                } else {
                    data = pyobj1.callAttr("onSendParamToMcu", "1", send_frequency_val.getSelectedItemPosition() + 1, packet_indx1, "40").toJava(byte[].class);

                }
                //data = pyobj1.callAttr("onSendParamToMcu", "1", send_frequency_val.getSelectedItemPosition() + 1, packet_indx1, send_voltage_val.getText().toString()).toJava(byte[].class);
                SocketQueueUtils.writeMsgByte(data);
                //kClearAllMuxBoxConnect 15
                data2 = pyobj1.callAttr("clear_mux", clearStrLisAll[0], clearStrLisAll[1], clearStrLisAll[2], clearStrLisAll[3], clearStrLisAll[4],
                        clearStrLisAll[5], clearStrLisAll[6], clearStrLisAll[7], clearStrLisAll[8], clearStrLisAll[9]).toJava(byte[].class);
                //kSetMuxBoxConnect 2
                data3 = pyobj1.callAttr("update_poles_connect", 1 + "," + abmnlis[0], 1 + "," + abmnlis[1],
                        1 + "," + abmnlis[2], 1 + "," + abmnlis[3]).toJava(byte[].class);

                loding_count = 1;

                try {
                    if (!startGater) {
                        Thread.sleep(1);
                    }

                    if (SocketQueueUtils.success_count < 7) {
                        onPause();
                        //System.out.println("===== 挂起=====");
                    }

                    try {
                        returnSta = recv_float_array_with_indx();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    if (returnSta) {
                        inclickGatherCount += 1;
                        abmn_indx += 1;
                        SocketQueueUtils.receiveDataAll = "";
                        SocketQueueUtils.packet_indx = 0;
                        SocketQueueUtils.packet_lens = 0;
                        SocketQueueUtils.packet_lens_old = 0;
                        SocketQueueUtils.success_count = 1;
                    }

                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

                rec_count_s = 0;
                //break;
                //no_id_str = "";
            }
        }
    }

    private void initData() {

        Sends sends = new Sends();
        Items items = findSelectItem();
        //sends.setId(1);
        sends.setItemId(items.getId());
        sendsService = new SendsService();
        //sendsService.updade(sends,new Sends());
        List<Sends> sendlis = sendsService.getSendsLast(sends);
        if (sendlis.size() > 0) {
            send_voltage_val.setText(sendlis.get(0).getVoltage());
            send_repeat_val.setText(sendlis.get(0).getRepeatNum());
            //send_frequency_val.setText(sendlis.get(0).getSendFrequency());
            send_frequency_val.setSelection(Integer.parseInt(sendlis.get(0).getSendFrequency()));
            //send_duration_val.setText(sendlis.get(0).getSendDuration());
            //clear_all_mux_box_connect_val.setText(sendlis.get(0).getBoxaddr());
        }
    }

    private Integer findSendCount() {
        Items items = findSelectItem();
        sendsService = new SendsService();
        List<Sends> lis = sendsService.getSends(new Sends(items.getId()));
        return lis.size();
    }

    private Integer findItemCount() {
        itemsService = new ItemsService();
        List<Items> lis = itemsService.getItems(new Items());
        return lis.size();
    }

    private Items findSelectItem() {
        itemsService = new ItemsService();
        Items items = new Items();
        Items items1 = new Items();
        items.setStatus(1);
        List<Items> lis = null;

        try {
            lis = itemsService.getItems(items);
            items1 = lis.get(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return items1;
    }

    /**
     * 保存后的弹框
     */
    private Boolean showPopupWindow() {

        //设置contentView
        contentView = LayoutInflater.from(myContext).inflate(R.layout.send_receive_add_pop, null);
        mPopWindow = new PopupWindow(contentView,
                ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT, true);
        mPopWindow.setContentView(contentView);
        mPopWindow.setTouchable(true); //设置是否响应触摸事件
        mPopWindow.setFocusable(false);//设置是否能获取焦点（如果控件中药EditText需要设置为true不然无法输入）
        mPopWindow.setOutsideTouchable(false);
        setAlpha(0.2f);
        mChart1 = contentView.findViewById(R.id.send_pop_chart);
        send_voltage_pop_val = contentView.findViewById(R.id.send_voltage_pop_val);
        send_repeat_pop_val = contentView.findViewById(R.id.send_repeat_pop_val);
        send_freq_pop_val = contentView.findViewById(R.id.send_freq_pop_val);
        receive_duration_pop_val = contentView.findViewById(R.id.receive_duration_pop_val);

        send_voltage_pop_val.setText(send_voltage_val.getText() + "v");
        send_repeat_pop_val.setText(send_repeat_val.getText() + "次");
        send_freq_pop_val.setText(sf + "hz");
        receive_duration_pop_val.setText(send_repeat_val.getText() + "秒");

        //显示PopupWindow
        View rootview = LayoutInflater.from(myContext).inflate(R.layout.send_receive_add, null);

        mPopWindow.showAtLocation(rootview, Gravity.BOTTOM, 0, 0);
        mChart1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //mPopWindow.setHeight(500);
                // mPopWindow.showAtLocation(rootview, Gravity.TOP, 0, 0);
                mChart1.setPivotX(mChart1.getWidth() / 2);
                mChart1.setPivotY(mChart1.getHeight() / 2);//支点在图片中心
                mChart1.setRotation(90);
                ViewGroup.LayoutParams params = mChart1.getLayoutParams();
                params.width = ScreenUtil.getScreenWidth(myContext);
                params.height = ScreenUtil.getScreenHeight(myContext);
                mChart1.setLayoutParams(params);
            }
        });
        //viewHolder.set
        pop_close = contentView.findViewById(R.id.send_pop_close);
        pop_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SocketQueueUtils.success_count = 0;
                try {
                    queue = null;
                    data = null;
                    data2 = null;
                    data3 = null;
                    receive_one_field_sta = false;
                    msg_sueecss_count = 0;
                    SocketQueueUtils.packet_indx = 0;
                    //SocketQueueUtils.buffer = null;
                    SocketQueueUtils.writeMsg("22,M;");

                    //111
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                //Toast.makeText(myContext, "关闭 === " + v.getId(), Toast.LENGTH_SHORT).show();

//                SocketQueueUtils.releaseSocket();
//                SocketQueueUtils = null;
                SocketQueueUtils.receiveDataAll = "";

                mPopWindow.dismiss();
                setAlpha(1.0f);
            }
        });

        //把背景还原
        mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                SocketQueueUtils.success_count = 5;
                setAlpha(1.0f);
            }
        });
        return true;
    }

//    private void setImageVal(String tx_voltage) {
//        //final ViewHolder viewHolder;
//        bytesData = null;
//        bytesData = pyobj.callAttr("sendCurve", tx_voltage).toJava(byte[].class);
//        mChart1.setImageBitmap(BitmapFactory.decodeByteArray(bytesData, 0, bytesData.length));
//    }

    private void initPython(Context myContext) throws JSONException, InterruptedException {
        //初始化python环境
        if (!Python.isStarted()) {
            Python.start(new AndroidPlatform(myContext));
        }

        py = Python.getInstance();
        //调用hello_python.py里面的plot函式
        pyobj = py.getModule("plotmy");
        pyobj1 = py.getModule("Send_Param");
        pyobj2 = py.getModule("Struct_Data");
        pyobj3 = py.getModule("earth_main");
        pyobjfft = py.getModule("fft_ui");

    }

    private void setAlpha(float f) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = f;
        getWindow().setAttributes(lp);
    }

    public class ViewHolder {

        public ImageView mChart1;

        public ViewHolder(View view, int position) {
            mChart1 = view.findViewById(R.id.send_pop_chart);

        }

    }


}